﻿/*
 * Copyright © 2011 Tristan Reeves, treeves@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
using System.Collections.Generic;
using System.Linq.Expressions;
using Sprinkles.Secondary;

namespace Sprinkles.ExpressionHandlers
{
    internal class ConstructorExpressionHandler<T>
    {
        private readonly List<Arg> m_Arguments = new List<Arg>();
        private bool ProcessInternal(NewExpression expression)
        {
            if (expression == null) return false;
            var ci = expression.Constructor;
            var args = expression.Arguments;

            if (!ci.IsPublic) return false;
            if (ci.DeclaringType != typeof(T)) return false;
            if (ci.GetParameters().Length != args.Count) return false;

            for (int i = 0; i < args.Count; i++)
            {
                var a = args[i] as ParameterExpression;
                if (a == null) return false;
                if (a.Type != ci.GetParameters()[i].ParameterType) return false;

                var item = new Arg();
                item.DeclaredType = a.Type;
                item.Name = ci.GetParameters()[i].Name;
                item.Index = i;
                m_Arguments.Add(item);
            }
            return true;
        }

        public void Process(LambdaExpression expression)
        {
            IsValid = false;

            var mce = expression.Body as NewExpression;
            if (mce == null) return;
            IsValid = ProcessInternal(mce);
        }
        public bool IsValid { get; private set; }
        public Arg[] Arguments { get { return m_Arguments.ToArray(); } }
    }
}
